/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.google.code.p.narcissus.ui.preferences;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

/**
 * @author jadoj
 */
public class ReferenceComments {

	private static File referenceCommentsFile;

	private static Map<String, String> referenceComments;

	private static final Logger LOGGER = Logger.getLogger(ReferenceComments.class);

	private ReferenceComments() {

	}

	public static void setReferenceCommentsFile(String filePath) {
		setReferenceCommentsFile(new File(filePath));
	}

	public static void setReferenceCommentsFile(File file) {
		if (file.exists() && file.isFile()) {
			referenceCommentsFile = file;
			referenceComments = null;
		}
	}

	public static String get(String referenceName) {
		if (referenceComments == null && referenceCommentsFile != null) {
			BufferedReader fileReader = null;
			try {
				fileReader = new BufferedReader(new FileReader(referenceCommentsFile));
				referenceComments = new HashMap<String, String>();
				String readLine = fileReader.readLine();
				while (readLine != null) {
					String[] splitLine = readLine.split(";");
					if (splitLine.length == 2) {
						referenceComments.put(splitLine[0], splitLine[1]);
					} else {
						referenceComments.put(splitLine[0],
								"ERROR - comment contains the ; character which is not permitted!  Ask Support team to have the file comments corrected");
					}
					readLine = fileReader.readLine();
				}
			} catch (IOException ex) {
				LOGGER.error(ex);
			} finally {
				if (fileReader != null) {
					try {
						fileReader.close();
					} catch (IOException e) {
						// Won't do anything about this one
					}
				}
			}
		}

		if (referenceComments != null) {
			return referenceComments.get(referenceName);
		} else {
			return null;
		}
	}
}
